// pages/category/category.js
const app = getApp()

Page({
  data: {
    categories: [],
    selectedCategoryId: null,
    products: [],
    searchKeyword: '',
    sortType: 'default', // default, sales, price
    priceOrder: 'asc', // asc, desc
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 20
  },

  onLoad(options) {
    // 处理从其他页面传来的参数
    if (options.featured) {
      this.loadFeaturedProducts()
    } else if (options.hot) {
      this.loadHotProducts()
    } else {
      this.loadCategories()
    }
  },

  onShow() {
    // 更新自定义tabBar的选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      });
    }

    // 检查是否有从首页传来的分类ID
    const selectedCategoryId = app.globalData.selectedCategoryId
    if (selectedCategoryId && selectedCategoryId !== this.data.selectedCategoryId) {
      this.setData({
        selectedCategoryId,
        page: 1,
        products: [],
        hasMore: true
      })
      this.loadProducts()
      app.globalData.selectedCategoryId = null // 清除标记
    }
  },

  onPullDownRefresh() {
    this.refreshData().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 刷新数据
  async refreshData() {
    this.setData({
      page: 1,
      products: [],
      hasMore: true
    })
    await this.loadProducts()
  },

  // 加载分类列表
  async loadCategories() {
    try {
      const response = await app.request({
        url: '/flowers/categories/'
      })
      
      // 后端返回的数据结构是 {success: true, data: [...]}
      const categories = response.data || []
      
      this.setData({
        categories,
        selectedCategoryId: categories.length > 0 ? categories[0].id : null
      })

      // 加载第一个分类的商品
      if (categories.length > 0) {
        this.loadProducts()
      }
    } catch (error) {
      console.error('加载分类失败:', error)
      // 如果分类接口不存在，直接加载所有商品
      this.setData({
        categories: [],
        selectedCategoryId: null
      })
      this.loadProducts()
    }
  },

  // 加载推荐商品
  async loadFeaturedProducts() {
    wx.setNavigationBarTitle({
      title: '精选推荐'
    })

    try {
      const response = await app.request({
        url: '/flowers/featured/',
        data: { limit: 50 }
      })

      if (response.success) {
        this.setData({
          products: response.data,
          categories: [],
          selectedCategoryId: null,
          hasMore: false
        })
      }
    } catch (error) {
      console.error('加载推荐商品失败:', error)
      app.showToast('加载失败', 'none')
    }
  },

  // 加载热销商品
  async loadHotProducts() {
    wx.setNavigationBarTitle({
      title: '热销榜单'
    })

    try {
      const response = await app.request({
        url: '/flowers/hot/',
        data: { limit: 50 }
      })

      this.setData({
        products: response.data || response.results || response || [],
        categories: [],
        selectedCategoryId: null,
        hasMore: false
      })
    } catch (error) {
      console.error('加载热销商品失败:', error)
      app.showToast('加载失败', 'none')
    }
  },

  // 加载商品列表
  async loadProducts(loadMore = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      const { selectedCategoryId, searchKeyword, sortType, priceOrder, page, pageSize } = this.data

      // 构建请求参数
      const params = {
        page: loadMore ? page : 1,
        page_size: pageSize
      }

      if (selectedCategoryId) {
        params.category_id = selectedCategoryId
      }

      if (searchKeyword) {
        params.search = searchKeyword
      }

      // 排序参数
      if (sortType === 'sales') {
        params.ordering = '-sales_count'
      } else if (sortType === 'price') {
        params.ordering = priceOrder === 'asc' ? 'price' : '-price'
      }

      const response = await app.request({
        url: '/flowers/',
        data: params
      })

      // app.request直接返回数据，不需要检查response.success
      const newProducts = response.results || []
      const hasMore = response.next ? true : false

      this.setData({
        products: loadMore ? [...this.data.products, ...newProducts] : newProducts,
        hasMore,
        page: loadMore ? page + 1 : 2
      })
    } catch (error) {
      console.error('加载商品失败:', error)
      app.showToast('加载商品失败', 'none')
    } finally {
      this.setData({ loading: false })
    }
  },

  // 分类选择
  onCategorySelect(e) {
    const categoryId = e.currentTarget.dataset.id || null
    if (categoryId === this.data.selectedCategoryId) return

    this.setData({
      selectedCategoryId: categoryId,
      page: 1,
      products: [],
      hasMore: true,
      searchKeyword: '' // 清空搜索
    })

    this.loadProducts()
  },

  // 更多选项点击
  onMoreTap() {
    wx.showActionSheet({
      itemList: ['推荐商品', '热销商品', '新品上架', '促销活动'],
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            // 推荐商品
            wx.navigateTo({
              url: '/pages/category/category?featured=1'
            })
            break
          case 1:
            // 热销商品  
            wx.navigateTo({
              url: '/pages/category/category?hot=1'
            })
            break
          case 2:
            // 新品上架
            wx.showToast({
              title: '敬请期待',
              icon: 'none'
            })
            break
          case 3:
            // 促销活动
            wx.showToast({
              title: '敬请期待',
              icon: 'none'
            })
            break
        }
      }
    })
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  // 搜索确认
  onSearchConfirm() {
    this.setData({
      page: 1,
      products: [],
      hasMore: true
    })
    this.loadProducts()
  },

  // 搜索点击
  onSearchTap() {
    // 可以跳转到专门的搜索页面
  },

  // 排序切换
  onSortChange(e) {
    const type = e.currentTarget.dataset.type
    let { sortType, priceOrder } = this.data

    if (type === 'price' && sortType === 'price') {
      // 如果已经是价格排序，切换升降序
      priceOrder = priceOrder === 'asc' ? 'desc' : 'asc'
    } else {
      sortType = type
      if (type === 'price' && priceOrder !== 'asc' && priceOrder !== 'desc') {
        priceOrder = 'asc'
      }
    }

    this.setData({
      sortType,
      priceOrder,
      page: 1,
      products: [],
      hasMore: true
    })

    this.loadProducts()
  },

  // 加载更多
  onLoadMore() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadProducts(true)
    }
  },

  // 商品点击
  onProductTap(e) {
    const productId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/detail/detail?id=${productId}`
    })
  }
})